﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.ComponentModel;


using Biblio2.LocalParsing;
using System.Collections.Generic;

namespace Biblio
{
    public class GetOnlineSerie : BackgroundWorker
    {
        #region Constructeur
        public GetOnlineSerie()
        {
            WorkerReportsProgress = true;
            WorkerSupportsCancellation = true;
        }
        #endregion Constructeur

        #region DoWork
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            List<LocalParseResult> localResultList = e.Argument as List<LocalParseResult>;

            if (localResultList != null)
            {
                //e.Result = ParsePathPairs(pathPairList);
            }

            if (e.Result == null)
                e.Cancel = true;
        }
        #endregion DoWork

        #region GetSeries
        private void GetSeries()
        {
            try
            {
                int iCpt = 0;
                foreach (CParseResult parseResult in listParseResult)
                {
                    worker.ReportProgress(iCpt, new CEventProgress(CEventProgress.EVENT_FOR_CURRENT_STEP, "Get Online Id Serie : " + iCpt.ToString() + "/" + listParseResult.Count.ToString(), listParseResult.Count));
                    if (parseResult.pathPair.m_iExisting == CPathPair.FILE_NOT_IN_DB)
                        COnlineSerieApi.GetSeries(parseResult);
                    iCpt++;
                }
                worker.ReportProgress(iCpt, new CEventProgress(CEventProgress.EVENT_FOR_CURRENT_STEP, "Get Online Id Serie : " + iCpt.ToString() + "/" + listParseResult.Count.ToString(), listParseResult.Count));
            }
            catch (Exception)
            {
            }

        }
        #endregion GetSeries

        #region GetSerie
        private void GetSerie()
        {


        }
        #endregion GetSerie

        /******************************************************************/
        // GetSeries
        public static void GetSeries(CParseResult parseResult)
        {
            try
            {
                if (parseResult.bSerieFound)
                {
                    if (parseResult.filenameParser.Matches.ContainsKey(CParserConst.csSerieName))
                    {
                        String sSeriesName = parseResult.filenameParser.Matches[CParserConst.csSerieName];
                        if (!sSeriesName.Equals(String.Empty))
                        {
                            if (!checkKnownSeries(parseResult))
                            {
                                XmlNodeList nodeList = GetSeriesXml(sSeriesName);
                                if (nodeList != null)
                                {
                                    int iSerieId;
                                    String sSerieNameFound;
                                    parseResult.m_DicoIdNameSerie.Clear();

                                    foreach (XmlNode itemNode in nodeList)
                                    {
                                        iSerieId = -1;
                                        sSerieNameFound = String.Empty;

                                        foreach (XmlNode propertyNode in itemNode.ChildNodes)
                                        {
                                            if (propertyNode.Name == COnlineAPI.m_sXmlNodeIdSerie)
                                            {
                                                try { iSerieId = Convert.ToInt32(propertyNode.InnerText); }
                                                catch (System.FormatException) { }
                                            }
                                            else if (propertyNode.Name == COnlineAPI.m_sXmlNodeSerieName)
                                            {
                                                sSerieNameFound = propertyNode.InnerText;
                                            }
                                        }

                                        if (sSerieNameFound.Trim().Equals(sSeriesName.Trim().ToLower(), StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            parseResult.sOnlineNameSerie = sSerieNameFound;
                                            parseResult.iIdOnlineSerie = iSerieId;
                                            CDataBase.updateSerie(iSerieId, sSerieNameFound, parseResult.bSerieFindAutoOnline, sSeriesName.Trim().ToLower(), true);
                                            parseResult.m_DicoIdNameSerie.Clear();
                                            return;
                                        }
                                        else
                                        {
                                            if (!parseResult.m_DicoIdNameSerie.ContainsKey(iSerieId))
                                                parseResult.m_DicoIdNameSerie.Add(iSerieId, sSerieNameFound);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /******************************************************************/
        // GetSeriesXml
        private static XmlNodeList GetSeriesXml(String sSeriesName)
        {
            try
            {
                String sUrl = String.Format(@"GetSeries.php?seriesname={0}&language=all", sSeriesName.Replace(' ', '+'));
                String sMirror = COnlineAPI.getMirror();
                if (sMirror.Equals(String.Empty))
                    return null;

                sUrl = COnlineAPI.appendAPI(sMirror, false) + sUrl;

                Stream data = COnlineAPI.RetrieveData(sUrl);

                if (data != null)
                {
                    StreamReader reader = new StreamReader(data);
                    String sXmlData = reader.ReadToEnd().Replace('\0', ' ');
                    data.Close();
                    reader.Close();
                    try
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(sXmlData);
                        XmlNode root = doc.FirstChild.NextSibling;
                        return root.ChildNodes;
                    }
                    catch (XmlException e)
                    {
                        MessageBox.Show("Xml parsing of " + sUrl + " failed (line " + e.LineNumber + " - " + e.Message + ")", "XML Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        throw e;
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return null;
        }
        /******************************************************************/
        //Check if the series name is in dictionnaire of online serie
        private static bool checkKnownSeries(CParseResult parseResult)
        {
            String sSeriesName = parseResult.filenameParser.Matches[CParserConst.csSerieName];
            CSerie serie = CDataBase.getSerieIdByName(sSeriesName.Trim().ToLower());
            if (serie != null)
            {
                parseResult.iIdOnlineSerie = serie.getId();
                parseResult.sOnlineNameSerie = serie.getTitle();
                return true;
            }
            return false;
        }
    }
}
